require(['framework', 'vueRouter', 'Vuex','404'],
    ({ajax, Vue, init, axios, HeyUI}, VueRouter, Vuex,Page404) => {

    Vue.use(VueRouter)
    Vue.use(Vuex)

    let router = new VueRouter({
        routes: [
            {
                path: '/login',
                name: 'Login',
                component: (r) => require(['login'], r)
            },
            {
                path: '/404',
                name: '404',
                component: Page404
            },
            {
                path: '/',
                name: 'Index',
                component: (r) => require(['index'], r),
                children: [
                    // {
                    //     path: '/',
                    //     name: 'Home',
                    //     component: (r) => require(['home'], r),
                    // }
                ]
            },
            {
                path: '*',
                redirect: '/404',
                name: 'notFound',
                hidden: true
            }
        ]
    })
    const addRoutes = (menus) => {
        for (let menu of menus) {
            if (menu.children) {
                addRoutes(menu.children)
            } else if (menu.path) {
                if (menu.path.endsWith(".vue")) {
                    router.addRoute('Index', {
                        name: menu.key,
                        path: menu.key=="Home" ? "/":menu.key,
                        meta:{
                            title:menu.title
                        },
                        component: (r) => {
                           // let path=menu.path.replace(/\.vue$/,'.js')
                            require([menu.path], r, (e) => {
                                if (e.status == 404 || e.message=='Failed to fetch') {
                                    router.push("/404")
                                }else{
                                    HeyUI.$Message({type:'error',text:e.statusText||e.message})
                                }
                            })
                        }
                    })
                } else {
                    router.addRoute({
                        name: menu.key,
                        path: menu.key,
                        meta:{
                            title:menu.title
                        },
                        props: {path: menu.path},
                        component: (r) => {
                            require(['coms/iframe'], r)
                        }
                    })
                }
            }
        }
    }
    const store = new Vuex.Store({
        state: {
            user: {},
            app: {}
        },
        actions: {
            loadUserInfo(ctx) {
                return new Promise((resolve, reject) => {
                    ajax.get('system/user_info').then(r => {
                        addRoutes(r.data.menu)
                        ctx.state.user = r.data
                        // r.data.menu.unshift({
                        //     icon:'h-icon-home',
                        //     key:'Home',
                        //     title:'首页'
                        // })
                        resolve(r)
                        if (router.currentRoute.name == "Login") {
                            router.push('/')
                        }
                    }).catch(e => {
                        reject(e)
                    })
                })
            }
        }
    })
    Vue.store=store
    const whiteList = ['Login', '404', '403']
    router.beforeEach((to, from, next) => {
        let name = to.name
        if (whiteList.indexOf(name) > -1) {
            if (name == 'Login') {
                let username = store.state.user.username
                if (username) {
                    next('/')
                } else {
                    next()
                }
            } else if(name=='Index'){
                next({name:'Home'})
            }else{
                next()
            }
        } else {
            let username = store.state.user.username
            if (!username) {
                next('/login')
            } else if(name=='Index'){
                next({name:'Home'})
            } else {
                next()
            }
        }
    })
    axios.interceptors.request.use(function(cfg){
        let token=sessionStorage['_token'];
        if(token){
            cfg.headers['token']=token
        }
        return cfg;
    })
    let showErrHandler
    //同时(10纳秒内)发生多个错误时，提示最后一个
    function showError(msg){
        clearTimeout(showErrHandler)
        showErrHandler=setTimeout(()=>{
            HeyUI.$Message({type: 'error', text: msg})
        },10);
    }
    axios.interceptors.response.use(function (res) {
        let isJson=res.headers['content-type'].indexOf('json')>-1;
        if (isJson && res.data && res.data.code != 200) {
            if (res.data.code == 401) {
                store.state.user={}
                location.hash = "/login"
                return Promise.reject(res.data);
            }else if(res.data.code == 403){
                //HeyUI.$Message({type: 'error', text: "没有权限！"})
                showError("没有权限！")
                return Promise.reject(res.data);
            }
            showError(res.data.description||res.data.data)
           // HeyUI.$Message({type: 'error', text: res.data.description})
            return Promise.reject(res.data)
        } else {
            let headers=res.headers
            let token=headers['token'];
            if(token){
                sessionStorage.setItem("_token",token);
            }else if(headers['rtk']){
                sessionStorage.removeItem("_token")
            }
            return isJson ? res.data:res;
        }
    }, function (error) {
        // 对响应错误做点什么;没有权限401，去登录界面
        if(!error.response){
            showError("网络错误！")
            //HeyUI.$Message({type: 'error', text: "网络错误！"})
        }else if (error.response.status === 401) {
            // window.$toast('登录超时')
            store.state.user={}
            location.hash = "/login"
        } else if (error.response.status === 403) {
            // window.$toast('暂无权限')
            //HeyUI.$Message({type: 'error', text: "没有权限！"})
            showError("没有权限！")
            location.hash = "/login"
        } else if (error.response.status === 500) {
            // window.$toast('网络错误')
            //HeyUI.$Message({type: 'error', text: "服务器错误！"})
            showError("服务器错误！")
        } else if (error.response.status === 404) {
            // window.$toast('网络错误')
            showError("页面未找到！")
           // HeyUI.$Message({type: 'error', text: "404 NOT FOUND！"})
        }else if(error.response.data){
            let data=error.response.data
            showError( data.description||data.data)
            //HeyUI.$Message({type: 'error', text: data.description||data.data})
        }
        return Promise.reject(error);
    });
    ajax.get("system/dict").then(res=>{
        let data=res.data
        for(let it in data){
            let items=data[it]
            HeyUI.addDict(it,items);
        }
    })
    store.dispatch('loadUserInfo').finally(e => {
        init("#app", {
            router,
            store
        })
    })
    //隔3分钟连一下，防止掉线
    setInterval(() => {
        ajax.get("system/keep").then(r=>{
            if(r.data&&r.data!=store.state.user.username){
                store.dispatch('loadUserInfo')
            }
        })
    }, 3*60*1000)
})
